package com.lkd.controller;

import com.lkd.dto.SkuDto;
import com.lkd.entity.Sku;
import com.lkd.service.ISkuService;
import com.lkd.utils.AliOssUtil;
import com.lkd.vo.PageBean;
import com.lkd.vo.Result;
import com.lkd.vo.SkuVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * ClassName: SkuController
 * Package: com.lkd.controller
 * Description:
 *
 * @Author zt
 * @Create 2025/10/10 10:53
 * @Version 1.0
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/vm-service/sku")
public class SkuController {
    private final AliOssUtil aliOssUtil;
    private final ISkuService skuService;

    /**
     * 图片上传
     */
    @PostMapping("/fileUpload")
    public Result upload(MultipartFile fileName) throws Exception{
        log.info("文件上传：{}", fileName);
        //构造一个文件名（不能重复），使用UUID
        String fileName1 = fileName.getOriginalFilename();  //获取原始文件名
        assert fileName1 != null;
        String extraName = fileName1.substring(fileName1.lastIndexOf('.'));
        String newFileName = UUID.randomUUID().toString() + extraName;

        // 将 MultipartFile 转为 InputStream
        InputStream inputStream = fileName.getInputStream();

        String url = aliOssUtil.upload(newFileName, inputStream);
        return Result.success(url);
    }

    /**
     * 新增商品
     */
    @PostMapping
    public Result save(@RequestBody Sku sku){
        //设置创建时间
        sku.setCreateTime(LocalDateTime.now());
        sku.setUpdateTime(LocalDateTime.now());
        skuService.save(sku);
        return Result.success();
    }

    /**
     * 商品搜索
     */
    @GetMapping("/search")
    public Result search(SkuDto skuDto){
        PageBean<SkuVo> pageBean =  skuService.search(skuDto);
        return Result.success(pageBean);
    }

    /**
     * 修改商品
     */
    @PutMapping
    public Result updateSku(@RequestBody Sku sku){
        sku.setUpdateTime(LocalDateTime.now());
        skuService.updateById(sku);
        return Result.success();
    }
}
